import React, {useEffect, useState} from 'react';
import {Button, Form, Input, message, Modal, Select, Space, Table, Tag} from 'antd';
import services from "../services";
import '../index.css'
import {PAGE_INIT, PageInfo} from "../type";
import {UserOutlined} from '@ant-design/icons';


const {Option} = Select;


const Teacher = () => {
    const [teacherList, setTeacherList] = useState([]);
    const [keyWord, setKeyWord] = useState(''); // 搜索关键字
    const [roleType, setRoleType] = useState(); // 角色类型
    const [pageInfo, setPageInfo] = useState<PageInfo>(PAGE_INIT);
    const [loading, setLoading] = useState(false); // 加载状态
    const [visible, setVisible] = useState(false); // 弹窗状态
    const [form] = Form.useForm();
    const [editTeacher, setEditTeacher] = useState({
        name: "",
        jobNumber: "",
        id: 0,
        roleType: 0
    }); // 编辑的教师信息
    const [editFlag, setEditFlag] = useState(false); // 是否编辑状态


    useEffect(() => {
        services.queryTeacher({keyWord: '', pageNum: PAGE_INIT.pageNum, pageSize: PAGE_INIT.pageSize}).then(data => {
            setPageInfo({...pageInfo, pageNum: data.pageNum, total: data.total});
            setTeacherList(data.list)
        });
    }, []);


    const OnQueryTeacher = () => {
        setTeacherList([])
        setLoading(true)
        services.queryTeacher({
            keyWord: keyWord,
            roleType: roleType,
            pageNum: pageInfo.pageNum,
            pageSize: pageInfo.pageSize
        }).then(data => {
            setPageInfo({...pageInfo, pageNum: data.pageNum, total: data.total});
            setTeacherList(data.list)
        }).finally(() => {
            setLoading(false)
        });
    }

    const OnDeleteTeacher = (record: any) => {
        services.deleteTeacher({teacherId: record.id}).then(data => {
            if (data.successFlag === true) {
                message.success('删除成功');
            } else {
                message.error('删除失败');
            }
        }).finally(() => {
            OnQueryTeacher();
        });
    }


    const OnEditTeacher = (record: any) => {
        setVisible(true);
        setEditFlag(true);
        setEditTeacher(record);
    }

    const OnAddTeacher = () => {
        setVisible(true);
        setEditFlag(false);
        // @ts-ignore
        setEditTeacher({});
    }


    const headers = [
        {
            width: 20,
            render: (text: any, record: any) => {
                return <div>
                    <UserOutlined/>
                </div>
            }
        },
        {
            title: '工号',
            width: 200,
            render: (text: any, record: any) => {
                return <div>
                    <span>{record.jobNumber}</span>
                </div>
            }
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            width: 200,
        },
        {
            title: '角色',
            render: (text: any, record: any) => {
                return <Tag color={record.roleType === 1 ? 'blue' : 'green'}>
                    {record.roleType === 1 ? '管理员' : '普通教师'}
                </Tag>
            }
        },
        {
            title: '操作',
            width: 200,
            render: (text: any, record: any) => {
                return <Space>
                    <Button onClick={() => OnEditTeacher(record)}>编辑</Button>
                    <Button type="primary" danger onClick={() => {
                        Modal.confirm({
                            title: '注销教师账号',
                            centered: true,
                            content: '是否注销工号为【 ' + record.jobNumber + ' 】，姓名为【 ' + record.name + ' 】的教师账号?',
                            okText: '确认注销',
                            onOk() {
                                OnDeleteTeacher(record);
                            },
                            cancelText: '取消',
                        });
                    }
                    }>注销教师账号</Button>
                    <Button type="link"
                            onClick={() => {
                                Modal.confirm({
                                    title: '重置密码',
                                    centered: true,
                                    content: '是否重置工号为【 ' + record.jobNumber + ' 】，姓名为【 ' + record.name + ' 】的教师账号密码?',
                                    okText: '确认重置',
                                    onOk() {
                                        services.resetPassword({teacherId: record.id}).then(data => {
                                            if (data === true) {
                                                message.success('重置成功');
                                            } else {
                                                message.error('重置失败');
                                            }
                                        });
                                    },
                                    cancelText: '取消',
                                });
                            }
                            }
                    >重置密码</Button>

                </Space>
            }
        },
    ]


    return <div>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
            <h1>教师花名册</h1>
            <Button className="custom-green-button" style={{margin: '20px 0 20px 30px'}}
                    onClick={OnAddTeacher}>添加教师账号</Button>
        </div>
        <div style={{marginBottom: '50px', display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
            <Space size={30}>
                <Input
                    placeholder="请输入工号或姓名进行搜索"
                    value={keyWord}
                    allowClear
                    onChange={(event) => {
                        setKeyWord(event.target.value);
                    }}
                    style={{width: '300px'}} // 设置样式
                />
                <Select style={{width: '200px'}}
                        allowClear={true} placeholder='请选择角色'
                        value={roleType} onChange={setRoleType}>
                    <Option value="0">普通教师</Option>
                    <Option value="1">管理员</Option>
                </Select>
                <Button type="primary" onClick={OnQueryTeacher}>查询</Button>
            </Space>
        </div>
        <div>
            <Table
                columns={headers}
                dataSource={teacherList}
                loading={loading}
                pagination={{
                    current: pageInfo.pageNum,
                    pageSize: pageInfo.pageSize,
                    total: pageInfo.total,
                }}
                onChange={(pagination, filters, sorter) => {
                    setPageInfo({
                        ...pageInfo,
                        pageNum: pagination.current || 1,
                        pageSize: pagination.pageSize || 15
                    });
                }}/>
        </div>


        <Modal
            title={editFlag ? '编辑教师' : '添加教师账号'}
            visible={visible}
            onOk={() => {
                services.updateOrAdd(editTeacher).then(data => {
                    if (data.successFlag === true) {
                        message.success(editFlag ? '修改成功' : "新增成功");
                        setVisible(false);
                        OnQueryTeacher();
                    } else if (data.successFlag === false) {
                        message.error(editFlag ? '修改失败' : "新增失败");
                    }
                });
            }

            }
            onCancel={() => {
                console.log(editTeacher)
                setVisible(false)
                // @ts-ignore
                setEditTeacher({});
            }}
            cancelText={'取消'}
            okText={editFlag ? '修改' : "新增"}
        >
            <div>
                <Form>

                    <Form.Item label={'id'} className='hidden-field'>
                        <Input placeholder="id" value={editTeacher.id}/>
                    </Form.Item>

                    <Form.Item label={'工号'}>
                        <Input placeholder="请输入工号" value={editTeacher.jobNumber}
                               onChange={(e) => {
                                   setEditTeacher({...editTeacher, jobNumber: e.target.value})
                               }}/>
                    </Form.Item>

                    <Form.Item label={'姓名'}>
                        <Input placeholder="请输入姓名" value={editTeacher.name}
                               onChange={(e) => {
                                   setEditTeacher({...editTeacher, name: e.target.value})
                               }}
                        />
                    </Form.Item>

                    <Form.Item label={'角色'}>
                        <Select style={{width: '200px'}}
                                allowClear={true}
                                placeholder='请选择角色'
                                onChange={(e) => {
                                    setEditTeacher({...editTeacher, roleType: Number(e)})
                                }}
                        >
                            <Option value="0">普通教师</Option>
                            <Option value="1">管理员</Option>
                        </Select>
                    </Form.Item>
                </Form>
            </div>
        </Modal>

    </div>
        ;

};

export default Teacher;
